#ifndef SOFTWARE_NAME
#define SOFTWARE_NAME "webconfig"
#endif
#ifndef VERSION
#define VERSION "NO VERSION"
#endif
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <microhttpd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define PORT            8888
int test;
static enum MHD_Result
send_msg (struct MHD_Connection *connection, const char *page)
{
  enum MHD_Result ret;
  struct MHD_Response *response;
  response = MHD_create_response_from_buffer_static (
      strlen (page), page);
  /*
  response = MHD_create_response_from_buffer (
      strlen (page), (void *)page, MHD_RESPMEM_PERSISTENT);
      */
  if (! response)
    return MHD_NO;
  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  MHD_destroy_response (response);
  return ret;
}
static enum MHD_Result
answer_to_connection (void *cls, struct MHD_Connection *connection,
                      const char *url, const char *method,
                      const char *version, const char *upload_data,
                      size_t *upload_data_size, void **req_cls)
{
 // enum MHD_Result ret;
  printf("%s\n", __func__);
  printf("method:%s url:%s\n", method, url);
  printf("data:%s\n", upload_data);
  if (NULL == *req_cls) {
    *req_cls = (void *)1;
    return MHD_YES;
  }
  if (0 == strcmp (method, "GET")) {
    return send_msg (connection, "\nget\n");
  }
  if (0 == strcmp (method, "POST")) {
    if (*upload_data_size != 0) {
      *upload_data_size = 0;
      *req_cls = strdup(upload_data);
      return MHD_YES;
    }
    char *data = (char *)*req_cls;
    printf("data:%s\n", data);
    free(data);
    return send_msg (connection, "\npost\n");
  }
  return send_msg (connection, "\ninvalid method\n");
}

//wget --post-data="key1=value1&key2=value2" http://127.0.0.1:8888/oint -O -
int main (void)
{
  int port = 8888;
  struct MHD_Daemon *daemon;

  daemon = MHD_start_daemon (
      MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
      port, NULL, NULL,
      &answer_to_connection, NULL,
      NULL, MHD_OPTION_END);
  if (NULL == daemon)
    return 1;
  printf("%d server port:%d\n", __LINE__,  port);
  (void) getchar ();
  MHD_stop_daemon (daemon);
  return 0;
}
